$(document).ready(function() {
    // 购物车功能
    let cart = JSON.parse(localStorage.getItem('cart')) || [];
    
    // 更新购物车数量显示
    function updateCartCount() {
        const totalItems = cart.reduce((total, item) => total + item.quantity, 0);
        $('#cartCount').text(totalItems);
    }
    
    // 渲染购物车内容
    function renderCart() {
        const $cartItems = $('#cartItems');
        const $cartTotalItems = $('#cartTotalItems');
        const $cartTotalPrice = $('#cartTotalPrice');
        
        if (cart.length === 0) {
            $cartItems.html('<div class="text-center text-muted py-4">购物车是空的</div>');
            $cartTotalItems.text('0件');
            $cartTotalPrice.text('¥0.00');
            return;
        }
        
        let itemsHtml = '';
        let totalPrice = 0;
        let totalItems = 0;
        
        cart.forEach((item, index) => {
            const itemTotal = item.price * item.quantity;
            totalPrice += itemTotal;
            totalItems += item.quantity;
            
            itemsHtml += `
                <div class="cart-item">
                    <img src="img/${item.img}" alt="${item.name}" class="cart-item-img">
                    <div class="cart-item-details">
                        <h6 class="cart-item-title">${item.name}</h6>
                        <div class="cart-item-price">¥${item.price.toFixed(2)}</div>
                        <div class="cart-item-quantity">
                            <button class="quantity-btn decrease" data-index="${index}">-</button>
                            <input type="text" class="quantity-input" value="${item.quantity}" readonly>
                            <button class="quantity-btn increase" data-index="${index}">+</button>
                            <span class="remove-item ms-2" data-index="${index}"><i class="bi bi-trash"></i></span>
                        </div>
                    </div>
                </div>
            `;
        });
        
        $cartItems.html(itemsHtml);
        $cartTotalItems.text(`${totalItems}件`);
        $cartTotalPrice.text(`¥${totalPrice.toFixed(2)}`);
        
        // 绑定数量增减和删除事件
        $('.decrease').on('click', function() {
            const index = $(this).data('index');
            if (cart[index].quantity > 1) {
                cart[index].quantity--;
            } else {
                cart.splice(index, 1);
            }
            saveCart();
            renderCart();
            updateCartCount();
        });
        
        $('.increase').on('click', function() {
            const index = $(this).data('index');
            cart[index].quantity++;
            saveCart();
            renderCart();
            updateCartCount();
        });
        
        $('.remove-item').on('click', function() {
            const index = $(this).data('index');
            cart.splice(index, 1);
            saveCart();
            renderCart();
            updateCartCount();
        });
    }
    
    // 保存购物车到本地存储
    function saveCart() {
        localStorage.setItem('cart', JSON.stringify(cart));
    }
    
    // 添加飞入动画的样式
    const styles = `
    <style>
        .flying-img {
            pointer-events: none;
            position: fixed;
            z-index: 9999;
            transition: all 0.8s ease;
        }
        
        .cart-bump {
            animation: bump 0.3s ease;
        }
        
        @keyframes bump {
            0% { transform: scale(1); }
            50% { transform: scale(1.2); }
            100% { transform: scale(1); }
        }
        
        .cart-item {
            display: flex;
            padding: 10px;
            border-bottom: 1px solid #eee;
        }
        
        .cart-item-img {
            width: 60px;
            height: 60px;
            object-fit: cover;
            margin-right: 10px;
        }
        
        .cart-item-details {
            flex: 1;
        }
        
        .quantity-btn {
            padding: 0 8px;
            border: 1px solid #ddd;
            background: #fff;
        }
        
        .quantity-input {
            width: 40px;
            text-align: center;
            border: 1px solid #ddd;
        }
    </style>
    `;

    $('head').append(styles);

    // 添加商品到购物车
    $('.add-to-cart').on('click', function() {
        const $this = $(this);
        const id = $this.data('id');
        const name = $this.data('name');
        const price = parseFloat($this.data('price'));
        const img = $this.data('img');
        
        // 获取商品卡片中的图片
        const $productImg = $this.closest('.card').find('img').eq(0);
        const $cart = $('.navbar .btn-outline-light[data-bs-toggle="offcanvas"]');
        
        // 创建飞入的图片元素
        const $flyImg = $('<img>', {
            src: `img/${img}`,
            class: 'flying-img',
            css: {
                'width': $productImg.width() + 'px',
                'height': $productImg.height() + 'px',
                'left': $productImg.offset().left + 'px',
                'top': $productImg.offset().top + 'px',
            }
        }).appendTo('body');

        // 获取购物车按钮的位置
        const cartOffset = $cart.offset();
        
        // 执行动画
        $flyImg.animate({
            width: 30,
            height: 30,
            left: cartOffset.left,
            top: cartOffset.top,
            opacity: 0.5
        }, {
            duration: 800,
            easing: 'swing',
            complete: function() {
                $flyImg.remove();
                
                // 添加到购物车
                const existingItem = cart.find(item => item.id === id);
                if (existingItem) {
                    existingItem.quantity++;
                } else {
                    cart.push({
                        id,
                        name,
                        price,
                        img,
                        quantity: 1
                    });
                }
                
                // 购物车图标动画
                $cart.addClass('cart-bump');
                setTimeout(() => {
                    $cart.removeClass('cart-bump');
                }, 300);
                
                saveCart();
                renderCart();
                updateCartCount();
                
                // 显示成功提示
                const $toast = $(`
                    <div class="toast position-fixed bottom-0 end-0 m-3" role="alert">
                        <div class="toast-header">
                            <strong class="me-auto">成功添加到购物车</strong>
                            <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
                        </div>
                        <div class="toast-body">
                            已将 ${name} 添加到购物车
                        </div>
                    </div>
                `).appendTo('body');
                
                const toast = new bootstrap.Toast($toast[0]);
                toast.show();
                
                setTimeout(() => {
                    $toast.remove();
                }, 3000);
            }
        });
    });
    
    // 结算按钮点击事件
    $('#checkoutBtn').on('click', function() {
        if (cart.length === 0) {
            alert('购物车是空的，请先添加商品');
            return;
        }
        
        // 添加确认对话框
        if (confirm('确认要提交订单吗？')) {
            // 显示成功提示
            const toast = `
                <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11">
                    <div class="toast show" role="alert">
                        <div class="toast-header">
                            <strong class="me-auto">订单提交成功</strong>
                            <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
                        </div>
                        <div class="toast-body">
                            感谢您的购买！我们将尽快处理您的订单。
                        </div>
                    </div>
                </div>
            `;
            
            $('body').append(toast);
            
            // 清空购物车
            cart = [];
            saveCart();
            renderCart();
            updateCartCount();
            
            // 关闭购物车侧边栏
            $('#shoppingCart').offcanvas('hide');
            
            // 3秒后移除提示
            setTimeout(() => {
                $('.toast').remove();
            }, 3000);
        }
    });
    
    // 初始化购物车
    updateCartCount();
    renderCart();
    
    // 搜索功能
    $('#searchInput').on('input', function() {
        const query = $(this).val().trim().toLowerCase();
        const $searchResults = $('#searchResults');
        
        if (query.length === 0) {
            $searchResults.hide();
            return;
        }
        
        // 模拟搜索数据
        const searchData = [
            { title: '汕头牛肉丸', url: 'specialty.html#food-section' },
            { title: '凤凰单丛茶', url: 'specialty.html#tea-section' },
            { title: '潮汕粿品', url: 'specialty.html#food-section' },
            { title: '南澳岛', url: 'scenery.html' },
            { title: '汕头美食', url: 'food.html' },
            { title: '汕头历史', url: 'history.html' }
        ];
        
        // 模糊匹配
        const results = searchData.filter(item => 
            item.title.toLowerCase().includes(query)
        );
        
        if (results.length > 0) {
            let html = '';
            results.forEach(item => {
                html += `<a href="${item.url}" class="search-result-item">${item.title}</a>`;
            });
            $searchResults.html(html).show();
        } else {
            $searchResults.html('<div class="p-3 text-muted">没有找到相关结果</div>').show();
        }
    });
    
    // 点击页面其他区域关闭搜索结果
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.search-form').length) {
            $('#searchResults').hide();
        }
    });
});